import { useState } from "react";
import SecurityContext from "../contexts/securutyContext";
import { get } from "@github/webauthn-json";

import { signin, logoutUser, startVerify, verify } from "../utils/api";

const SecurityProvider = ({ children }) => {
  const [loggedIn, setLoggedIn] = useState(false);

  const login = async (username, password) => {
    const user = await signin(username, password);
    user && setLoggedIn(true);
  };

  const loginWithToken = async (userID) => {
    const response = await startVerify(userID);
    const assertion = await get({ publicKey: response});

    await verify(userID, assertion)
    setLoggedIn(true)
  };

  const logout = async () => {
    await logoutUser();
    setLoggedIn(false);
  };

  return (
    <SecurityContext.Provider
      value={{
        login,
        logout,
        loginWithToken,
        loggedIn,
      }}
    >
      {children}
    </SecurityContext.Provider>
  );
};

export default SecurityProvider;
